package 通用数据转换器;

import java.lang.reflect.Method;

public class DtoConverter {
    /**
     * 通用DTO转换方法
     * @param source 源对象
     * @param targetClass 目标类
     * @return 转换后的DTO对象
     */
    public static <S, T> T convert(S source, Class<T> targetClass) {
        if (source == null)
        {
            return null;
        }
        
        try {
            T target = targetClass.getDeclaredConstructor().newInstance();//必须提供一个无参构造器
            copyProperties(source, target);
            return target;
        } catch (Exception e) {
            throw new RuntimeException("DTO转换失败", e);
        }
    }
    /**
     * 通用属性拷贝方法
     * @param source 源对象
     * @param target 目标对象
     */
    public static <S, T> void copyProperties(S source, T target) {
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();

        for (Method sourceMethod : sourceClass.getMethods()) {
            if (sourceMethod.getName().startsWith("get") && sourceMethod.getParameterCount() == 0) {
                String propertyName = sourceMethod.getName().substring(3);
                try {
                    Method targetMethod = targetClass.getMethod("set" + propertyName, sourceMethod.getReturnType());
                    Object value = sourceMethod.invoke(source);
                    targetMethod.invoke(target, value);
                } catch (NoSuchMethodException e) {
                    // 目标对象没有对应的setter方法，跳过该属性
                    continue;
                } catch (Exception e) {
                    throw new RuntimeException("属性拷贝失败: " + propertyName, e);
                }
            }
        }
    }
}
